import React, { useState, useEffect, useRef, useCallback, memo, useMemo } from 'react';
import {
  Input,
  List,
  Card,
  Typography,
  Avatar,
  Drawer,
  Skeleton,
  Space,
  Spin,
  DatePicker,
  Button,
  message,
} from 'antd';
import { Search } from '@/components/eai-design';
import Empty from '@/components/NotData';
import styles from '../styles/UserTable.module.css';
import '../styles/styles.css';
import { SvgIcon } from '@/components/icon';
import { debounce } from 'lodash';
import { CalendarOutlined, SearchOutlined } from '@ant-design/icons';

const { Title, Text } = Typography;

// import MessageList from '@/pages/chat/components/MessageList';
import MessageList from '@/pages/app-qa/components/chat/components/MessageList';

import DefaultRobot from '@/assets/icons/ic_robot.svg';
import reportService from '@/api/services/reportService';
import { userListItem, questionListItem, messageItem, pageReq } from '@/common/types';
import { useParams } from '@/router/hooks';

import useWindowWidth from '@/hooks/event/use-window-width';
import dayjs from 'dayjs';

import VirtualList from 'rc-virtual-list';
import { useThemeToken } from '@/theme/hooks';

import { useVirtualList } from 'ahooks';
const { RangePicker } = DatePicker;
import { CalendarPicker } from 'antd-mobile';
import { ToolModuleResponseItemType } from '@/types/chat/type';
import { useOrchestrationStore } from '@/store/orchestrationStore';
import TipDesc from '@/components/tipDesc/tipDesc';

interface UserQuestionsProps {
  users: userListItem[];
  userCount: number;
  selectedRole: string;
  dateRange?: any;
}

const UserItem = memo(({ user, onClick, isSelected, colorPrimary, index, isPc }) => {
  return (
    <div
      onClick={onClick}
      // className={isSelected && isPc ? `${styles.selected}` : ''}
      style={{
        cursor: 'pointer',
        padding: '10px',
        borderRadius: '6px',
        // borderBottom: '1px solid #e8e8e8',
        border: isSelected ? '1px solid #8EC5FF' : '1px solid #F7F8FA',
        backgroundColor: isSelected ? '' : '#F7F8FA',
        marginBottom: '6px',
      }}
      key={index}
    >
      <div className="flex items-center">
        {/* <Avatar
            className="ml-auto h-10 w-10"
            style={{ marginRight: '10px',  backgroundColor: colorPrimary }}
          >
            {user?.username[0]}
          </Avatar> */}
        <span
          className="ant-avatar ant-avatar-circle custome-avatar"
          style={{ marginRight: '10px', backgroundColor: colorPrimary }}
        >
          <span className="ant-avatar-string">{user?.username[0]}</span>
        </span>
        <div>
          <span className="text-sm font-semibold text-text-5" style={{ paddingRight: '20px' }}>
            {user.username}
          </span>
          <span className="text-text-5">{user.studentId}</span>
          <br />
          <div className="flex gap-2 text-sm">
            <span className="text-text-3">累计使用 {user?.usageDays || 0 + 1} 天</span>
            <span className="text-text-3">共提问 {user?.questionCount || 0} 次</span>
          </div>
        </div>
      </div>
    </div>
  );
});

const UserQuestions = ({ users, userCount, selectedRole, dateRange = [] }: UserQuestionsProps) => {
  const { colorPrimary } = useThemeToken();

  const [searchValue, setSearchValue] = useState('');
  const [containerHeight, setContainerHeight] = useState(800);
  const [selectedUser, setSelectedUser] = useState<userListItem>();
  const [selectedQuestion, setSelectedQuestion] = useState<questionListItem | null>(null);
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [mobileQuestionVisible, setMobileQuestionVisible] = useState(false);
  const [exportLoading, setExportloading] = useState(false);
  const [messages, setMessages] = useState<messageItem[]>([]);
  const { isPc } = useWindowWidth();

  const { appId: id } = useParams() as { appId: string };

  const defaultPage = { page: 1, page_size: 20 };
  const [page, setPage] = useState<pageReq>(defaultPage);
  const listRef = useRef<HTMLDivElement>(null);

  const containerRef = useRef(null);
  const wrapperRef = useRef(null);
  const [userQaLoading, setUserQaLoading] = useState(false);
  const [qaScrollLoading, setQaScrollLoading] = useState(false);
  const [qaCount, setQaCount] = useState(200);

  const [qaPage, setQaPage] = useState({ page: 1, pageSize: 10, offset: 0 });
  const [drawerHasMore, setDrawerHasMore] = useState(true);
  const [drawerLoadingMore, setDrawerLoadingMore] = useState(false);
  const drawerChatIdRef = useRef<string | null>(null);

  const [filterLoading, setFilterLoading] = useState(false);
  const [filteredUsers, setFilteredUser] = useState<userListItem[]>([]);
  const [filterCount, setFilterCount] = useState(0);

  const defaultUserPage = { page: 1, page_size: 100 };
  const [userPage, setUserPage] = useState<pageReq>(defaultUserPage);
  const [isUserFetchMore, setIsUserFetchMore] = useState(true);

  const [rangePickerValue, setRangePickerValue] = useState();

  const { appDetail } = useOrchestrationStore();

  const onRangePickerChange = (dates) => {
    if (dates) {
      const formattedDates = dates.map((date) => date.format('YYYY-MM-DD'));
      setRangePickerValue(formattedDates);
      console.log('日期范围选择值:', formattedDates);
    } else {
      setRangePickerValue([]);
      console.log('日期范围选择值: 无');
    }
  };

  const [visible, setVisible] = useState(false);

  const handleIconClick = () => {
    setVisible(true); // 点击图标时显示日期选择器
  };

  // useEffect(()=>{
  //   if (searchValue) {
  //     setFilteredUser(users.filter(
  //       (user) =>
  //         user.username?.toLowerCase().includes(searchValue.toLowerCase())
  //     ))
  //   } else {
  //     setFilteredUser(users)
  //   }
  // }, [searchValue])

  const fetchUserByKeyWord = async () => {
    setIsUserFetchMore(true);
    setUserPage(defaultUserPage);
    // if (!searchValue && rangePickerValue.length == 0) {
    //   setFilteredUser(users);
    //   userSelected(users?.[0]);
    //   users?.length > 0 && fetchQuestionUserList(id, users[0], defaultPage, rangePickerValue);
    // } else {
    fetchUser();
    // }
    if (containerRef?.current) {
      containerRef?.current?.scrollTo(0, 0);
    }
  };

  useEffect(() => {
    fetchUserByKeyWord();
  }, [searchValue, rangePickerValue]);
  // 监听 dateRange 变化
  useEffect(() => {
    if (dateRange && dateRange.length === 2) {
      setRangePickerValue(dateRange.map((date: dayjs.Dayjs) => date.format('YYYY-MM-DD')));
    }
  }, [dateRange]);

  const fetchUser = async (
    page = defaultUserPage?.page,
    page_size = defaultUserPage?.page_size,
  ) => {
    try {
      if (rangePickerValue == undefined) {
        return;
      }
      setFilterLoading(true);
      const { data, count } = await reportService.appUserList(
        id,
        selectedRole,
        page,
        page_size,
        searchValue,
        rangePickerValue,
      );
      console.log(data?.length, count, filterCount, filteredUsers?.length);
      if (data?.length == filteredUsers?.length) {
        setIsUserFetchMore(false);
      }
      setFilteredUser(data);
      setFilterCount(count);
      if (page_size == defaultUserPage?.page_size && data?.length == 0) {
        setSelectedUser(undefined);
      }

      data?.length > 0 && fetchQuestionUserList(id, data[0], defaultPage, rangePickerValue);
    } catch (error) {
    } finally {
      setFilterLoading(false);
    }
  };

  const [list] = useVirtualList(filteredUsers, {
    containerTarget: containerRef,
    wrapperTarget: wrapperRef,
    itemHeight: 71,
    overscan: 50,
  });

  const showDrawer = useCallback(
    async (question: questionListItem) => {
      setMessages([]);
      setDrawerVisible(true);
      setQaPage({ page: 1, pageSize: 10, offset: 0 });
      setDrawerHasMore(true);
      drawerChatIdRef.current = question.id as any;

      const [start, end] =
        Array.isArray(rangePickerValue) && (rangePickerValue as any).length === 2
          ? (rangePickerValue as any)
          : ['', ''];
      const response: any = await reportService.qAList(question.id as any, start, end, 1, 10, 0);

      const list = (response as any)?.list ?? (response as any)?.data ?? response ?? [];
      const textList = list.map((item: any) => {
        let textContent = '';
        let interactive: any = {};
        let toolJson: Record<string, ToolModuleResponseItemType> = {};
        if (item?.value && Array.isArray(item.value)) {
          item.value.forEach((valueItem: any) => {
            if (valueItem?.type === 'tool') {
              if (valueItem.tools?.length > 0) {
                valueItem.tools.forEach((toolData: any) => {
                  if (toolData?.id) {
                    textContent += `__TOOL_CALL_${toolData.id}__\n`;
                    toolJson[toolData.id] = {
                      id: toolData.id,
                      toolName: toolData.toolName || '',
                      toolAvatar: toolData.toolAvatar || '',
                      functionName: toolData.functionName || '',
                      params: toolData.new_args || toolData.params || '',
                      response: toolData.response || '',
                    };
                  }
                });
              }
            } else if (valueItem?.type === 'interactive') {
              interactive = valueItem?.interactive;
            } else if (valueItem?.type === 'text' && valueItem?.text?.content) {
              textContent += valueItem.text.content + '\n';
            }
          });
        }

        return {
          text: textContent || '',
          toolJson: toolJson,
          interactive: interactive,
          params: (interactive as any)?.params,
          time: dayjs(item?.time).format('YYYY-MM-DD HH:mm:ss'),
          isUser: item?.obj === 'Human',
          quote: item?.totalQuoteList || [],
          username: selectedUser?.username,
          userGoodFeedback: item?.userGoodFeedback,
          userBadFeedback: item?.userBadFeedback,
          appName: item?.appName || '',
          appLogo: item?.appLogo || '',
          appType: appDetail?.appType || '',
          appId: item?.appId || '',
          shareId: item?.shareId || '',
        } as any;
      });

      setMessages(textList);
      setSelectedQuestion(question);
      setDrawerHasMore((list?.length ?? 0) > 0);
    },
    [selectedUser, appDetail?.appType, rangePickerValue],
  );

  const loadMoreDrawerMessages = useCallback(async () => {
    if (!drawerHasMore || drawerLoadingMore) return;
    if (!drawerChatIdRef.current) return;
    try {
      setDrawerLoadingMore(true);
      const nextPage = qaPage.page + 1;
      const nextOffset = (nextPage - 1) * qaPage.pageSize;
      const [start, end] =
        Array.isArray(rangePickerValue) && (rangePickerValue as any).length === 2
          ? (rangePickerValue as any)
          : ['', ''];
      const response: any = await reportService.qAList(
        drawerChatIdRef.current,
        start,
        end,
        nextPage,
        qaPage.pageSize,
        nextOffset,
      );
      const list = (response as any)?.list ?? (response as any)?.data ?? response ?? [];
      const appendList = list.map((item: any) => {
        let textContent = '';
        let interactive: any = {};
        let toolJson: Record<string, ToolModuleResponseItemType> = {};
        if (item?.value && Array.isArray(item.value)) {
          item.value.forEach((valueItem: any) => {
            if (valueItem?.type === 'tool') {
              if (valueItem.tools?.length > 0) {
                valueItem.tools.forEach((toolData: any) => {
                  if (toolData?.id) {
                    textContent += `__TOOL_CALL_${toolData.id}__\n`;
                    toolJson[toolData.id] = {
                      id: toolData.id,
                      toolName: toolData.toolName || '',
                      toolAvatar: toolData.toolAvatar || '',
                      functionName: toolData.functionName || '',
                      params: toolData.new_args || toolData.params || '',
                      response: toolData.response || '',
                    };
                  }
                });
              }
            } else if (valueItem?.type === 'interactive') {
              interactive = valueItem?.interactive;
            } else if (valueItem?.type === 'text' && valueItem?.text?.content) {
              textContent += valueItem.text.content + '\n';
            }
          });
        }

        return {
          text: textContent || '',
          toolJson: toolJson,
          interactive: interactive,
          params: (interactive as any)?.params,
          time: dayjs(item?.time).format('YYYY-MM-DD HH:mm:ss'),
          isUser: item?.obj === 'Human',
          quote: item?.totalQuoteList || [],
          username: selectedUser?.username,
          userGoodFeedback: item?.userGoodFeedback,
          userBadFeedback: item?.userBadFeedback,
          appName: item?.appName || '',
          appLogo: item?.appLogo || '',
          appType: appDetail?.appType || '',
          appId: item?.appId || '',
          shareId: item?.shareId || '',
        } as any;
      });
      setMessages((prev) => [...prev, ...appendList]);
      setQaPage({ ...qaPage, page: nextPage, offset: nextOffset });
      if ((appendList?.length ?? 0) === 0) setDrawerHasMore(false);
    } finally {
      setDrawerLoadingMore(false);
    }
  }, [
    drawerHasMore,
    drawerLoadingMore,
    qaPage,
    rangePickerValue,
    selectedUser,
    appDetail?.appType,
  ]);

  useEffect(() => {
    if (!drawerVisible) return;

    let retryTimer: number | null = null;
    const cleanupHandlers: Array<() => void> = [];

    const bind = () => {
      const chatList = document.querySelector('.chat-list') as HTMLDivElement | null;
      const drawerBodies = document.querySelectorAll('.ant-drawer-body');
      const drawerBody = drawerBodies.length
        ? (drawerBodies[drawerBodies.length - 1] as HTMLDivElement)
        : null;

      if (!chatList && !drawerBody) {
        retryTimer = window.setTimeout(bind, 120);
        return;
      }

      const handler = (el: HTMLDivElement) => {
        const onScroll = () => {
          if (el.scrollTop + el.clientHeight >= el.scrollHeight - 20) {
            loadMoreDrawerMessages();
          }
        };
        el.addEventListener('scroll', onScroll);
        cleanupHandlers.push(() => el.removeEventListener('scroll', onScroll));
      };

      if (chatList) handler(chatList);
      if (drawerBody) handler(drawerBody);
    };

    bind();

    return () => {
      if (retryTimer) clearTimeout(retryTimer);
      cleanupHandlers.forEach((fn) => fn());
    };
  }, [drawerVisible, messages.length, loadMoreDrawerMessages]);

  const onCloseDrawer = useCallback(() => {
    setDrawerVisible(false);
  }, []);

  useEffect(() => {
    setContainerHeight(window.innerHeight);
    setFilteredUser(users);
  }, []);

  useEffect(() => {
    console.log('aaaaaaaaaaaaa1');

    // if (users?.length > 0 && id) {
    //   setPage(defaultPage);
    //   fetchQuestionUserList(id, users[0], defaultPage, rangePickerValue);
    // }
  }, [users, id]);

  const abortControllerRef = useRef<AbortController | null>(null);

  const fetchQuestionUserList = useCallback(
    async (id: string, user: userListItem, searchPage: pageReq = defaultPage, rangeData = []) => {
      try {
        const abortController = new AbortController();
        const { signal } = abortController;

        // 如果之前有未完成的请求，取消
        if (abortControllerRef.current) {
          abortControllerRef.current.abort();
        }
        abortControllerRef.current = abortController;

        if (searchPage.page == 1 && searchPage.page_size == 20) {
          setUserQaLoading(true);
          if (listRef.current) {
            listRef.current.scrollTop = 0; // 滚动到顶部
          }
        }
        setSelectedUser({ ...user });
        if (!user?.id) {
          return;
        }

        if (rangeData.length == 2) {
          searchPage.startTime = rangeData[0];
          searchPage.endTime = rangeData[1];
        }

        const response = await reportService.questionUserList(id, user.id, searchPage, signal);
        setQaCount(response?.count);
        const textList = response?.questions?.map((question, index) => {
          return {
            ...question,
            text: question?.title,
            username: selectedUser?.username,
          };
        });
        // if (searchPage.page != 1) {
        //   user.questions = [...(user.questions || []), ...textList];
        // } else {
        //   user.questions = textList;
        // }
        user.questions = textList;
        console.log(user.questions?.length);
        setSelectedUser({ ...user });
      } catch (error) {
        if (error.name === 'CanceledError') {
          console.log('Request aborted');
        } else {
          console.error(error);
        }
      } finally {
        setUserQaLoading(false);
      }
    },
    [selectedUser],
  );

  const userSelected = useCallback(
    (user: userListItem) => {
      setPage(defaultPage);
      id && fetchQuestionUserList(id, user, defaultPage, rangePickerValue);
    },
    [id, fetchQuestionUserList],
  );

  const handleScrollUser = (event: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
    if (
      scrollHeight - scrollTop - clientHeight < 300 &&
      !filterLoading &&
      filteredUsers?.length < filterCount &&
      isUserFetchMore
    ) {
      fetchUser(userPage?.page, userPage.page_size + defaultUserPage?.page_size);
      setUserPage({ ...userPage, page_size: userPage.page_size + defaultUserPage?.page_size });
    }
  };

  const handleScroll = (event: React.UIEvent<HTMLDivElement>) => {
    const { scrollTop, scrollHeight, clientHeight } = event.currentTarget;
    console.log(scrollTop, scrollHeight, clientHeight, scrollHeight - scrollTop - clientHeight);
    if (
      scrollHeight - scrollTop - clientHeight < 2 &&
      (selectedUser?.questions?.length || 0) < (qaCount || 200)
    ) {
      if (id && selectedUser) {
        // fetchQuestionUserList(id, selectedUser, {...page, page: page.page + 1});
        // setPage({...page, page: page.page + 1})

        try {
          setQaScrollLoading(true);
          fetchQuestionUserList(
            id,
            selectedUser,
            {
              ...page,
              page_size: page.page_size + defaultPage?.page_size,
            },
            rangePickerValue,
          );
          setPage({ ...page, page_size: page.page_size + defaultPage?.page_size });
        } catch (error) {
        } finally {
          setQaScrollLoading(false);
        }
      }
    }
  };

  const handleSearchChange = useCallback(
    debounce((value) => {
      setSearchValue(value);
    }, 300),
    [],
  );

  return (
    <div
      style={{
        display: 'flex',
        flexDirection: 'column',
        width: '100%',
        height: isPc ? '38vh' : '100%',
        // backgroundColor: '#fff',
        padding: isPc ? ' 0px' : '0',
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          width: '100%',
          // height: isPc ? '50vh' : '30vh',
          height: '100%',
          backgroundColor: '#fff',
          boxSizing: 'border-box',
          // border: '1px solid green',
          padding: isPc ? '16px' : '8px',
        }}
        className="rounded-default "
      >
        <div
          style={{
            display: !isPc ? 'flex' : 'unset',
            justifyContent: !isPc ? 'space-between' : 'unset',
            alignItems: !isPc ? 'center' : 'unset',
          }}
        >
          {/* <span className={`${styles.statistic_span} ml-3 mt-2`}>总用户数: {filteredUsers.length}</span> */}
          <div
            className={`${styles.statistic_span} ml-3 `}
            style={{ height: '40px', display: 'flex', alignItems: 'center' }}
          >
            {isPc ? (
              <div className="flex w-full items-center justify-between">
                <div>
                  <SvgIcon color="#1B6DFA" icon="Ellipse" style={{ marginRight: '8px' }}></SvgIcon>
                  注册用户数：{filterCount || 0}
                  <span
                    style={{
                      fontSize: '12px',
                      fontWeight: 300,
                      alignContent: 'end',
                      color: 'rgb(142, 147, 164)',
                    }}
                  >
                    （以下仅显示提问的用户）
                  </span>
                </div>
                <div className="flex items-center">
                  <Search
                    onChange={(e) => handleSearchChange(e.target.value)}
                    placeholder="输入用户名"
                  />
                  <Button
                    className="ml-2"
                    style={{ color: '#1B6DFA', border: '1px solid #1B6DFA' }}
                    loading={exportLoading}
                    onClick={async () => {
                      try {
                        setExportloading(true);
                        const res = await reportService.exportQAData(
                          id,
                          rangePickerValue,
                          searchValue,
                        );
                        if (res?.download_url) {
                          // 创建一个隐藏的a标签来下载文件
                          const link = document.createElement('a');
                          link.href = res.download_url;
                          link.style.display = 'none';
                          document.body.appendChild(link);
                          link.click();
                          // 清理DOM
                          document.body.removeChild(link);
                        } else {
                          message.error('导出失败，未获取到下载链接');
                        }
                      } catch (error) {
                        console.error('导出数据失败:', error);
                        // message.error('导出数据失败')
                      } finally {
                        setExportloading(false);
                      }
                    }}
                  >
                    导出数据
                  </Button>
                </div>
              </div>
            ) : (
              `注册用户数：${filterCount || 0}`
            )}
          </div>
          <TipDesc
            title="统计平台累计注册的用户总数，直观反映平台的用户基础规模"
            className="!my-0 ml-3"
          />
          {isPc && (
            <div className="flex">
              {/* <div className="px-2">
                <RangePicker
                  // className="piker-border piker-radio"
                  onChange={onRangePickerChange}
                  value={rangePickerValue.map((date) => dayjs(date))}
                />
              </div> 
               <Input
                prefix={<SearchOutlined />}
                placeholder="输入用户名"
                allowClear
                onChange={(e) => handleSearchChange(e.target.value)}
                style={{
                  width: '200px',
                  borderRadius: '6px',
                  // borderWidth: '0px',
                  // backgroundColor: '#ECEFF8',
                }}
              />
              <Button
                className="ml-2"
                style={{ color: '#1B6DFA', border: '1px solid #1B6DFA' }}
                loading={exportLoading}
                onClick={async () => {
                  try {
                    setExportloading(true);
                    const res = await reportService.exportQAData(id, rangePickerValue, searchValue);
                    if (res?.download_url) {
                      // 创建一个隐藏的a标签来下载文件
                      const link = document.createElement('a');
                      link.href = res.download_url;
                      link.style.display = 'none';
                      document.body.appendChild(link);
                      link.click();
                      // 清理DOM
                      document.body.removeChild(link);
                    } else {
                      message.error('导出失败，未获取到下载链接');
                    }
                  } catch (error) {
                    console.error('导出数据失败:', error);
                    // message.error('导出数据失败')
                  } finally {
                    setExportloading(false);
                  }
                }}
              >
                导出数据
              </Button> */}
            </div>
          )}
          {!isPc && (
            <>
              <CalendarOutlined
                onClick={handleIconClick}
                style={{
                  fontSize: '24px',
                  marginRight: '10px',
                  cursor: 'pointer',
                  color: colorPrimary,
                }}
              />
              {visible && (
                <CalendarPicker
                  visible={visible}
                  defaultValue={rangePickerValue}
                  className="custom-calendar-picker"
                  style={{
                    '--adm-color-primary': colorPrimary,
                  }}
                  min={new Date(2024, 1, 1)}
                  selectionMode="range"
                  onClose={() => {
                    setVisible(false);
                  }}
                  onMaskClick={() => setVisible(false)}
                  onChange={(val) => {
                    if (val?.length == 2) {
                      console.log(val);
                      const dayjsDate0 = dayjs(val[0]).format('YYYY-MM-DD');
                      const dayjsDate1 = dayjs(val[1]).format('YYYY-MM-DD');
                      console.log(dayjsDate0);
                      setRangePickerValue([dayjsDate0, dayjsDate1]);
                    } else {
                      setRangePickerValue([]);
                    }
                  }}
                />
              )}
            </>
          )}
        </div>

        {isPc ? (
          <div style={{ display: 'flex', flex: 1, minHeight: 0, overflow: 'hidden' }}>
            <div className="h-full p-2" style={{ minHeight: 0 }}>
              {/* <div>
                <Search
                  placeholder="输入用户名"
                  allowClear
                  onChange={(e) => handleSearchChange(e.target.value)}
                  style={{ width: 200 }}
                />
                <Input
                  prefix={<SearchOutlined />}
                  placeholder="输入用户名"
                  allowClear
                  onChange={(e) => handleSearchChange(e.target.value)}
                  style={{
                    width: '100%',
                    borderRadius: '6px',
                    borderWidth: '0px',
                    backgroundColor: '#ECEFF8',
                  }}
                />
              </div>
              <div className='p-2'>
                <RangePicker />
              </div> */}
              <div
                style={{
                  width: '20%',
                  minWidth: '300px',
                  // borderRight: '1px solid #e8e8e8',
                  // border: "1px solid red",
                  height: '100%',
                  // marginTop: '10px',
                  // overflowX: 'hidden',
                  minHeight: 0,
                }}
                className={`hide-scrollbar h-full flex-1 overflow-auto`}
                ref={containerRef}
                onScroll={handleScrollUser}
              >
                <div ref={wrapperRef} style={{ position: 'relative', overflow: 'visible' }}>
                  {list.map(({ data: user, index, style }) => (
                    <div key={`${user.id}-wrap`} style={style}>
                      <UserItem
                        key={user.id}
                        user={user}
                        index={index}
                        onClick={() => userSelected(user)}
                        isSelected={selectedUser && selectedUser.id === user.id}
                        colorPrimary={colorPrimary}
                        isPc={isPc}
                      />
                    </div>
                  ))}
                  {/* {filterLoading && (
                    <div style={{ textAlign: 'center', padding: '20px' }}>
                      <Spin />
                    </div>
                  )} */}
                </div>
              </div>
            </div>

            <div
              style={{
                padding: '10px 20px 24px',
                height: '100%',
                minHeight: 0,
                boxSizing: 'border-box',
              }}
              className={`hide-scrollbar h-full flex-1 overflow-auto`}
              ref={listRef}
              onScroll={handleScroll}
            >
              {selectedUser ? (
                userQaLoading ? (
                  <Skeleton />
                ) : (
                  <List
                    dataSource={selectedUser?.questions || []}
                    footer={
                      <>
                        {qaScrollLoading && (
                          <div style={{ textAlign: 'center', padding: '20px' }}>
                            <Spin />
                          </div>
                        )}
                      </>
                    }
                    renderItem={(question) => (
                      <List.Item
                        onClick={() => showDrawer(question)}
                        style={{ cursor: 'pointer', borderBottom: '1px solid #F2F3F5' }}
                      >
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <Text className="!text-text-5">{question.text}</Text>
                          <Text
                            type="secondary"
                            className="!text-text-3"
                            style={{ marginTop: '5px' }}
                          >
                            {dayjs(question?.time).format('YYYY-MM-DD HH:mm:ss')}
                          </Text>
                        </div>
                      </List.Item>
                    )}
                    locale={{ emptyText: <Empty /> }}
                  />
                )
              ) : (
                <Empty />
              )}
            </div>
          </div>
        ) : (
          <div>
            <div className="mb-2 p-2">
              {/* <Input
                prefix={<SearchOutlined />}
                placeholder="输入用户名"
                allowClear
                onChange={(e) => handleSearchChange(e.target.value)}
                style={{
                  width: '100%',
                  borderRadius: '6px',
                  borderWidth: '0px',
                  backgroundColor: '#ECEFF8',
                }}
              /> */}
              <Search
                onChange={(e) => handleSearchChange(e.target.value)}
                placeholder="输入用户名"
              />
            </div>
            <div
              ref={containerRef}
              style={{
                display: 'flex',
                flex: 1,
                overflowY: 'auto',
                // border: '1px solid red',
                height: '200px',
              }}
              className={`${styles.hide_scrollbar_2}`}
              onScroll={handleScrollUser}
            >
              <div
                ref={wrapperRef}
                style={{
                  width: '100%',
                  minWidth: '300px',
                  borderRight: '1px solid #e8e8e8',
                  position: 'relative',
                  overflow: 'visible',
                }}
                className={`${styles.hide_scrollbar_2}`}
              >
                {list.map(({ data: user, index, style }) => (
                  <div key={`${user.id}-wrap-m`} style={style}>
                    <UserItem
                      key={user.id}
                      user={user}
                      index={index}
                      onClick={() => {
                        userSelected(user);
                        setMobileQuestionVisible(true);
                      }}
                      isSelected={selectedUser && selectedUser.id === user.id}
                      colorPrimary={colorPrimary}
                      isPc={isPc}
                    />
                  </div>
                ))}
                {/* {filterLoading && (
                  <div style={{ width: '100%', textAlign: 'center', padding: '20px' }}>
                    <Spin />
                  </div>
                )} */}
              </div>
            </div>
          </div>
        )}

        {!isPc && (
          <Drawer
            title={
              <div
                style={{
                  display: 'flex',
                  justifyContent: 'space-between',
                  height: '46px',
                  alignItems: 'center',
                }}
              >
                <span
                  style={{
                    fontSize: '20px',
                    fontWeight: 500,
                    color: '#474C5F',
                  }}
                >
                  对话列表
                </span>
              </div>
            }
            open={mobileQuestionVisible}
            onClose={() => {
              setMobileQuestionVisible(false);
            }}
            width="100%"
            zIndex={100}
            closeIcon={<SvgIcon icon="ic-back" size={24} />}
            className="custom-drawer-header flex justify-between pt-2"
          >
            <div style={{ width: '100%' }}>
              {selectedUser ? (
                <List
                  className="custom-list"
                  footer={
                    qaScrollLoading && (
                      <div style={{ textAlign: 'center', padding: '20px' }}>
                        <Spin />
                      </div>
                    )
                  }
                >
                  <VirtualList
                    data={selectedUser?.questions || []}
                    height={containerHeight}
                    itemKey="id"
                    onScroll={handleScroll}
                  >
                    {(question: questionListItem) => (
                      <List.Item onClick={() => showDrawer(question)} style={{ cursor: 'pointer' }}>
                        <div style={{ display: 'flex', flexDirection: 'column' }}>
                          <Text>{question.text}</Text>
                          <Text type="secondary" style={{ marginTop: '5px' }}>
                            {dayjs(question?.time).format('YYYY-MM-DD HH:mm:ss')}
                          </Text>
                        </div>
                      </List.Item>
                    )}
                  </VirtualList>
                </List>
              ) : (
                <Empty />
              )}
            </div>
          </Drawer>
        )}

        <Drawer
          title={<div className="text-xl font-semibold text-text-5">对话记录</div>}
          open={drawerVisible}
          onClose={onCloseDrawer}
          width={isPc ? 900 : '100%'}
          zIndex={200}
          style={{ padding: '0px 20px' }}
          closeIcon={isPc ? undefined : <SvgIcon icon="ic-back" size={24} />}
          className={isPc ? 'custom-pc-header' : 'custom-drawer-header flex justify-between pt-2'}
        >
          {selectedQuestion && (
            <div>
              {/* <MessageList
                messages={messages}
                robotAvatar={DefaultRobot}
                username={selectedUser?.username}
                colorPrimary={colorPrimary}
                isMetaHuman={false}
                isAudioPlaying={false}
                isMuted={false}
                isChat={false}
              /> */}
              <div style={{ width: '100%', maxWidth: isPc ? 840 : '100%', margin: '0 auto' }}>
                <MessageList messages={messages} isChat={false} />
              </div>
              {drawerLoadingMore && (
                <div style={{ textAlign: 'center', padding: '12px 0' }}>
                  <Spin />
                </div>
              )}
            </div>
          )}
        </Drawer>
      </div>
    </div>
  );
};

export default UserQuestions;
